//
//  ServicePlatfomMineViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/5/8.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
import CRRefresh

class ServicePlatfomMineViewController: BaseViewController {

    @IBOutlet var myReleaseBtn: UIButton!
    
    @IBOutlet var myJoinBtn: UIButton!
    
    @IBOutlet var segmentView: UIView!
    
    
    @IBOutlet var myPlatformTableview: UITableView!
    
    
    var plaformSegment:YJSegmentedControl?
    
    var titleStatus = 1 // 0 我的发布  1 我参与
    
    var taskStatus = 0 // 0 已发布  1 已完成  2已关闭
    
    var platformTasks:[PlatformTaskModel]?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        page = 1
        self.requstPlatformTaskList(page: page!, status: (self.taskStatus),type:(self.titleStatus))
        
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configView()
        initSegmentControl()
        self.myReleaseBtn.isSelected = true
        self.myJoinBtn.isSelected = false
    }
    
    @IBAction func myReleaseBtnPress(_ sender: UIButton) {
        self.myReleaseBtn.isSelected = true
        self.myJoinBtn.isSelected = false
        page = 1
        titleStatus = 0
        self.requstPlatformTaskList(page: page!, status: (self.taskStatus),type:(self.titleStatus))
        
    }
    
    @IBAction func myJoinBtnPress(_ sender: UIButton) {
        self.myReleaseBtn.isSelected = false
        self.myJoinBtn.isSelected = true
        page = 1
        titleStatus = 1
        self.requstPlatformTaskList(page: page!, status: (self.taskStatus),type:(self.titleStatus))
    }
    
    
    func initSegmentControl() -> Void {
//        let btnDataSource = ["已发布","已完成","已关闭"]
        let btnDataSource = ["已参与","已签约","已关闭"]
        plaformSegment = YJSegmentedControl.init(frame: CGRect(x:0,y:0,width:kScreenWidth - 100,height:self.segmentView.frame.height), titleDataSource: btnDataSource, backgroundColor: UIColor.clear, titleColor: BaseColor.DarkGrayColor, titleFont: UIFont.systemFont(ofSize: 14), select: BaseColor.NavColor, buttonDownColor: BaseColor.NavColor, delegate: self)
        plaformSegment?.center.x = kScreenWidth/2
        self.segmentView.addSubview(plaformSegment!)
    }
    
    func configView() -> Void {
        myPlatformTableview.delegate = self
        myPlatformTableview.dataSource = self
        myPlatformTableview.separatorStyle = .none
        myPlatformTableview.showsVerticalScrollIndicator = false
        //            appointmentTableview.backgroundColor = UIColor.color(.OXe1e1e1)
        myPlatformTableview.register(UINib(nibName: "ServiceMineTaskTableViewCell", bundle: nil), forCellReuseIdentifier: "mineplatformCell")
        myPlatformTableview.cr.addHeadRefresh(animator: SlackLoadingAnimator() as CRRefreshProtocol) { [weak self] in
            page = 1
            self?.requstPlatformTaskList(page: page!, status: (self?.taskStatus)!,type:(self?.titleStatus)!)
        }
        myPlatformTableview.cr.addFootRefresh(animator: SlackLoadingAnimator() as CRRefreshProtocol)  { [weak self] in
            page! += 1
            self?.requstPlatformTaskList(page: page!, status: (self?.taskStatus)!,type:(self?.titleStatus)!)
        }
    }
    
    
    //网络请求
    func requstPlatformTaskList(page:Int,status:Int,type:Int) -> Void {
        
        var urlStr :String?
        switch type {
        case 0:
            urlStr = getMineReleaseTaskListUrl
        case 1:
            urlStr = getMineJoinTaskListUrl
        default:
            break
        }
        
        
        Alamofire.request(urlStr!, method:.post, parameters: ["status":status,"page": page,"uid":UserModel.shareUser.data?.uid ?? String()])
            .responseString { response in
                
                self.myPlatformTableview?.cr.endHeaderRefresh()
                self.myPlatformTableview?.cr.endLoadingMore()
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<BaseArrayData<PlatformTaskModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        if page == 1 {
                            self.platformTasks?.removeAll()
                            self.platformTasks = basemodel.data?.data
                        }else {
                            if ((basemodel.data?.data?.count)! > 0) {
                                self.platformTasks! += (basemodel.data?.data)!
                            }else {
                                return
                            }
                        }
                        self.myPlatformTableview.reloadData()
                        print("数据成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                case false:
                    print(response.result.error!)
                }
                
                
        }
    }
    
    //跳转查看需求页面
    func pushLookServiceTaskVC(model:PlatformTaskModel) -> Void {
        let lookServiceTaskVC = LookServiceViewController()
        lookServiceTaskVC.title = "需求详情"
        lookServiceTaskVC.taskModel = model
        self.navigationController?.pushViewController(lookServiceTaskVC, animated: true)
    }
    //跳转修改需求页面
    func pushEditServiceTaskVC(model:PlatformTaskModel) -> Void {
        let editServiceTaskVC = EditServiceTaskViewController()
        editServiceTaskVC.title = "我的需求详情"
        editServiceTaskVC.taskModel = model
        self.navigationController?.pushViewController(editServiceTaskVC, animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

extension ServicePlatfomMineViewController: YJSegmentedControlDelegate,UITableViewDelegate,UITableViewDataSource {
    
    func segumentSelectionChange(_ selection: Int) {
        page = 1
        taskStatus = selection
        self.requstPlatformTaskList(page: page!, status: (self.taskStatus),type:(self.titleStatus))
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.platformTasks?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "mineplatformCell", for: indexPath) as! ServiceMineTaskTableViewCell
        cell.selectionStyle = .none
        let model = platformTasks![indexPath.row]
        cell.contentLabel.text = model.describe
        cell.priceLabel.text = "预算:¥" + model.budget_money
        cell.userHeaderImageView.sd_setImage(with: (NSURL(string:(model.shead_url))! as URL), placeholderImage: UIImage.init(named: "defultHeaderImg"))
        cell.userNameLabel.text = model.sname
        cell.taskTypeLabel.text = model.name
        cell.taskNumLabel.text = model.count + "个方案"
        if model.status == "2" {
            cell.contentLabel.textColor = UIColor.HexColor(0xeeeeee)
            cell.priceLabel.textColor = UIColor.HexColor(0xeeeeee)
            cell.userNameLabel.textColor = UIColor.HexColor(0xeeeeee)
            cell.taskTypeLabel.textColor = UIColor.HexColor(0xeeeeee)
            cell.taskTypeLabel.layer.borderColor = UIColor.HexColor(0xeeeeee).cgColor
            cell.taskNumLabel.textColor = UIColor.HexColor(0xeeeeee)
            cell.detailsBtn.textColor = UIColor.HexColor(0xeeeeee)
        }else {
            cell.contentLabel.textColor = UIColor.HexColor(0x353535)
            cell.priceLabel.textColor = UIColor.HexColor(0xFF7200)
            cell.userNameLabel.textColor = UIColor.HexColor(0x353535)
            cell.taskTypeLabel.textColor = UIColor.HexColor(0x353535)
            cell.taskTypeLabel.layer.borderColor = UIColor.HexColor(0x353535).cgColor
            cell.taskNumLabel.textColor = UIColor.HexColor(0x353535)
            cell.detailsBtn.textColor = UIColor.HexColor(0x35B0AB)
            
        }
       
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return ScaleHeight(100)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = platformTasks![indexPath.row]
        
        if model.state == "0"{//0 与我无关
            
            
        }else if model.state == "1"{//1 我发布
            
            switch model.status {
            case "0"://已发布
                self.pushEditServiceTaskVC(model: model)
            case "1"://已完成
                self.pushLookServiceTaskVC(model: model)
            default://已关闭
                
                break
            }
        }else {//2 我参与
            switch model.status {
            case "0"://已发布
                self.pushLookServiceTaskVC(model: model)
            case "1"://已完成
                self.pushLookServiceTaskVC(model: model)
            default://已关闭
                
                break
            }
        }
        
    }
}
